package top.csmcool.musicapi.fliter;

import cn.dev33.satoken.stp.StpUtil;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;

@WebFilter("/admin/*")
public class AdminFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        // 过滤器初始化逻辑
        System.out.println("AdminFilter 初始化完成");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;

        String path = httpRequest.getRequestURI();

        // 检查路径是否以 /admin 开头
        if (path.startsWith("/admin") && !StpUtil.isLogin() && !StpUtil.getLoginId().equals("1")) {
            // 拒绝访问并返回 403 Forbidden
            httpResponse.sendError(HttpServletResponse.SC_FORBIDDEN, "你没有权限访问该资源");
            return;
        }

        // 继续传递请求
        chain.doFilter(request, response);
    }

    @Override
    public void destroy() {
        // 过滤器销毁逻辑
        System.out.println("AdminFilter 销毁完成");
    }
}